package com.lmx.persistence.service;

import java.util.List;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Assessment;

/**
 * 员工考核service实现
 *
 * @author ytche
 * @date 2017年6月28日
 *
 */
@Service(value = "assessmentService")
public class AssessmentServiceImpl extends BaseCrudServiceImpl<Assessment> implements
		AssessmentService {
	@Autowired
	private DicttypeService dicttypeService;

	@Override
	public Assessment save(Assessment entity) {
		if (entity.getId() == null) {
			Assessment existAssessment = this.getExistAssessment(entity);
			return existAssessment == null ? super.create(entity) : existAssessment;
		}
		// 防止前端修改信息的时候会将总分清空
		if (entity.getPoint() == null) {
			entity.setPoint(super.findOne(entity.getId()).getPoint());
		}
		Assessment old = super.findOne(entity.getId());
		if (!old.getExamTime().equals(entity.getExamTime())
				&& this.getExistAssessment(entity) != null) {
			throw new BusinessException("",
					CommonConstants.ASSESSMENT_ERROR.CHANGE_ASSESSMENT_EXIST.lable(), "修改信息存在");
		}
		return super.update(entity);
	}

	/**
	 * 获取已经存在的考核
	 *
	 * @author ytche
	 * @param entity
	 * @return
	 * @date 2017年8月9日 下午3:24:10
	 */
	@SuppressWarnings("unchecked")
	private Assessment getExistAssessment(Assessment entity) {
		Integer examTime = entity.getExamTime();
		Integer startTime = CommonUtil.getDayBegin(examTime);
		Integer endTime = CommonUtil.getDayBegin(new DateTime(examTime.longValue() * 1000)
				.plusDays(1).toDate());
		String queryStr = "from Assessment as a where a.delStatus=0 and "
				+ "a.examiner.id=:examinerId and a.type.id=:typeId and a.examTime>=:startTime and a.examTime<:endTime";
		List<Assessment> assessments = super.em.createQuery(queryStr)
				.setParameter("examinerId", entity.getExaminer().getId())
				.setParameter("typeId", entity.getType().getId())
				.setParameter("startTime", startTime).setParameter("endTime", endTime)
				.getResultList();
		return assessments != null && assessments.size() > 0 ? assessments.get(0) : null;
	}
}
